package com.hk.service.impl;

import com.hk.commons.*;
import com.hk.commons.entity.LogUtil;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.Parameter;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.vo.CheckInfo;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IOrganization;
import com.hk.service.IOrganization_New;
import com.hk.service.kyc.ILogUtil;
import com.hk.service.order.IParameter;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;
import org.hibernate.internal.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class OrganizationImpl extends BaseServiceImpl<Organization> implements
		IOrganization {

	private Logger logger = LoggerFactory.getLogger(OrganizationImpl.class);

	@Autowired
	private IParameter parmService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private ILogUtil logService;

	@Autowired
	private ISysUserRoles roleService;

	@Autowired
	private ISysUserRoles sysUserRolesService;

	@Autowired
	private IOrganization_New orgNewService;

	@Override
	public Organization findById(Integer id) {
		return getById(id);
	}

	@Override
	public CheckInfo check(Organization u) {
		CheckInfo checkinfo = new CheckInfo();
		checkinfo.setResult(true);

		//检查无主客户服务部是否已存在
		if(u.getDepType()== ConstantOrg.ORG_TYPE_WUZHU){

			HqlFilter hqlFilter = new HqlFilter();
			hqlFilter.addSql(" where 1=1 and status= 1 and parentId = " + u.getParentID() + "  and depType =  " + ConstantOrg.ORG_TYPE_WUZHU);
			logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql());
			Long size = this.countByFilter(hqlFilter);
			logger.info("size = " + size );
			if(size.compareTo(Long.valueOf("0")) > 0){
				checkinfo.setResult(false);
				checkinfo.setResultMsg("该部门下已存在无主客户服务部！");
			}else{
				checkinfo.setResult(true);
			}
		}

		return checkinfo;
	}

	//create in 2016
	@Override
	public Integer add(Organization model) {

		// 保存
		Integer id = save(model);

		Organization org = getById(id);

		// 加入助记码
		if (org.getParentID() != null) {
			Organization parentOr = findById(org.getParentID());
			if (parentOr != null) {
				org.setCode(parentOr.getCode() + "-" + id);
			}
		} else {
			org.setCode(id.toString());
		}

		super.update(org);

		org = getById(id);
		org.setFlag02(getDepNameById(org.getId()));
		org.setFullName(getDepNameById(org.getId()));

		Organization orgPar = findById(org.getParentID());
		org.setChannel(orgPar.getChannel());

		org.setCts(System.currentTimeMillis());
		// 更新
		super.update(org);
		return id;
	}

	//create in 2016
	public String getChannelNameByChannel(int channel){
		String channelName=null;
		switch (channel) {
		case ConstantUserChannel.USER_CHANNEL_JUJIAN:
			channelName="居间渠道部";
			break;
		case ConstantUserChannel.USER_CHANNEL_NEIQU_01:
			channelName="内部渠道1部";
			break;
		case ConstantUserChannel.USER_CHANNEL_NEIQU_02:
			channelName="内部渠道2部";
			break;
		case ConstantUserChannel.USER_CHANNEL_WUZHU:
			channelName="无主客户部";
			break;
		case ConstantUserChannel.USER_CHANNEL_ZHIXIAO_01:
			channelName="直销1部";
			break;
		case ConstantUserChannel.USER_CHANNEL_ZHIXIAO_02:
			channelName="直销2部";
			break;
		case ConstantUserChannel.USER_CHANNEL_ZONGHE:
			channelName="综合业务部";
			break;
		default:
			channelName="无主客户部";
			break;
		}
		return channelName;
	}

	//create in 2016
	public String getChannelName(int orgId) {
		Organization organization = findById(orgId);
		String orgCode = organization.getCode();
		if (orgCode.startsWith(ConstantOrgEnum.ALL_BUSINESS)) {
			return "综合业务部";
		} else if (orgCode.startsWith(ConstantOrgEnum.DIRECTSALE_ONE)) {
			return "直销1部";
		} else if (orgCode.startsWith(ConstantOrgEnum.DIRECTSALE_TWO)) {
			return "直销2部";
		} else if (orgCode.startsWith(ConstantOrgEnum.IN_MIDDLE)) {
			return "居间渠道部";
		} else if (orgCode.startsWith(ConstantOrgEnum.INNERSALE_ONE)) {
			return "内部渠道1部";
		} else if (orgCode.startsWith(ConstantOrgEnum.INNERSALE_TWO)) {
			return "内部渠道2部";
		} else {
			return "其他渠道";
		}
	}

	//create in 2016
	public Integer save(Organization model) {
		return (Integer) super.save(model);
	}

	//create in 2016
	@Override
	public Organization delete(Integer id, Long actUserId) {
		// TODO Auto-generated method stub
		Organization model = this.findById(id);
		model.setStatus(0);
		update(model, actUserId);
		return model;
	}

	//create in 2016
	@Override
		public CheckInfo deleteCheck(Integer id) {
		CheckInfo checkInfo = new CheckInfo();
		checkInfo.setResult(true);

		Organization org = findById(id);

		HqlFilter hqlFilter = new HqlFilter();
		if(org.getOrgType() == 3){
			String orgCode = org.getCode();
			hqlFilter.addSql(" where 1=1 and status = 1 and code like '" + orgCode + "-%'");
			Long size = countByFilter(hqlFilter);
			logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql() + " size ="  + size.longValue() );
			if(size.longValue() > 0){
				checkInfo.setResult(false);
				checkInfo.setResultMsg("请转移/删除下级公司/部门/职务后再删除！" );
			}
		}else if(org.getOrgType() == 4){
			hqlFilter.addEQFilter("orgId", id);
			Long size = userService.countByFilter(hqlFilter);

			if(size.longValue() > 0){
				checkInfo.setResult(false);
				checkInfo.setResultMsg("请转移/删除下级" + size.longValue() + "位人员后再删除！" );
			}
		}

		return checkInfo;
	}

	@Override
	public void update(Organization u, Long actUserId) {

		/**日志开始**/
		LogUtil logRecord = new LogUtil();

		logRecord.setActUserId(actUserId);
		logRecord.setType(ConstantLog.LOG_TYPE_ORG);

		String orgFullName = "";
		if (StringHelper.isNotEmpty(u.getName())) {
			orgFullName = u.getName();
		}
		logRecord.setChgDesc("修改组织架构 组织架构名称为   : " + orgFullName);


		logRecord.setRecordId(Long.valueOf(u.getId()));
		logRecord.setUserId(null);

		// 在日志表中保存修改之前的镜像

		Organization org  = findById(u.getId());
		String beforeImgStr = JsonUtils.toJson(org);
		logRecord.setBeforeImg(beforeImgStr);

		super.update(u);

		/**日志开始**/
		String afterImgStr = JsonUtils.toJson(u);
		logRecord.setAfterImg(afterImgStr);

		// 加入日志表中
		logService.add(logRecord);
	}

	//create in 2016
	@Override
	public List<Organization> findByUser(Long userId) {
		if(userId == null){
			logger.info("userId is null will return, userId = " + userId);
			return null;
		}

		HqlFilter hqlFilter = new HqlFilter();

		SysUser user = userService.findById(userId);
		if(user.getOrgId() == null ){
			logger.info("user orgId is null will return, userId = " + userId);
			return  null;
		}
		Integer orgId = user.getOrgId();

		Organization org = findById(orgId);
		if(org == null || StringHelper.isEmpty(org.getCode())){
			logger.info("org  is null will return ");
			return null;
		}

		String orgCode =  this.getDepCodeByDuties(orgId);


		//是渠道负责人
		if(roleService.isDepLeader(Long.valueOf(userId)) ) {
			logger.info("user is leader, userId ={}", userId);

			String appendSql = " channel = -1 " ;

			List<Integer> channelIdList = orgNewService.getDepLeaderChannelStrList(Long.valueOf(userId));

			for (Integer channelId : channelIdList) {
				logger.info(" channelId ={}", channelId);
				appendSql += " or channel = " + channelId;
			}

			hqlFilter.addSql(" where 1=1 and status = 1 and ( " +  appendSql  + " )");

		}else if (sysUserRolesService.isChannelRegis(userId)) {
			hqlFilter.addSql(" where 1=1 and status = 1 and code like '" + orgCode + "%'");
		}else if(sysUserRolesService.isOperationalManager(userId)){
			hqlFilter.addSql(" where 1=1 and status = 1 and id != 1 and id != 2" );
		}else{
			return null;
		}

		logger.info("hqlFilter = " + hqlFilter.getWhereAndOrderHql());


		List<Organization> orgList = this.findByFilter(hqlFilter);
		if(orgList != null){
			logger.info("orgList size  " + orgList.size());

		}else{
			logger.info("orgList size  " +  0);
			orgList = new ArrayList<Organization>();
		}

		//如果只是渠道录入人员，则添加其父部们
		if(sysUserRolesService.isChannelRegis(userId)){
			String[] codeArray = orgCode.split("-");
			for (int i = 0; i < codeArray.length; i++) {
				Integer parentId = Integer.valueOf(codeArray[i]);
				if(parentId != 1 && parentId != 2){
					Organization parent = getById(parentId);
					orgList.add(parent);
				}
			}
		}


		Organization parent = getById(1);
		orgList.add(parent);

		parent = getById(2);
		orgList.add(parent);


		return orgList;
	}

	//create in 2016
	public String getDepNameById(Integer id) {
		String name = "";

		Organization model = getById(id);
		String[] idsStr = model.getCode().split("-");
		for (int i = 0; i < idsStr.length; i++) {
			Integer parentId = Integer.valueOf(idsStr[i]);
			Organization parent = getById(parentId);
			if (parent.getOrgType().equals(Constant.ORGANIZATION_TYPE_DEPARTMENT) || parent.getOrgType().equals(Constant.ORGANIZATION_TYPE_DUTIES)) {
				name = name + "-" + parent.getName();
			}
		}

		return name.substring(1, name.length());
	}

	//create in 2016
	@Override
	public String getDepCode(String code, Integer orgId) {
		String returnCode = null;
		returnCode = code.replace(orgId.toString(), "");
		return returnCode;
	}

	//create in 2016
	@Override
	public String getOrgLeaderCodeByOrgId(Integer orgId) {

		Organization org = findById(orgId);
		String code = org.getCode();

		// 如果是部分负责人，则获取相应的组织架构的节点
		if (org.getIsHeader() == 1) {
			code = getLeaderCodeByCode(code, orgId);
		}

		return code;
	}

	//create in 2016
	@Override
	public String getLeaderCodeByCode(String code, Integer orgId) {
		logger.info("code ={}, orgId ={}", code, orgId);
		String returnCode = null;

		List<Parameter> parmList = parmService
				.getByFlag(ConstantParm.PARM_CODE);
		for (Parameter parm : parmList) {
			if (parm.getName().equals(code)) {
				returnCode = parm.getValue01();
				System.out.println("returnCode = " + returnCode);
				break;
			}
		}

		if (returnCode == null) {
			logger.info("returnCode is null");
			returnCode = getDepCode(code, orgId);

		}

		logger.info("returnCode ={}", returnCode);

		return returnCode;
	}

	//create in 2016
	@Override
	public String getOrgFileter(Integer channelId) {
		String result = " 2 = 2";
		switch (channelId) {
		// 内部渠道一部
		case 1:
			result = " orgId in (select id from com.hk.commons.entity.Organization where "
					+ "  code like '1-2-5-%')";
			break;

		// 内部渠道二部
		case 2:
			result = " orgId in (select id from com.hk.commons.entity.Organization where "
					+ "  code like '1-2-4-%')";
			break;

		// 直销渠道部
		case 3:
			result = " orgId in (select id from com.hk.commons.entity.Organization where "
					+ "  code like '1-2-3-%')";
			break;

		// 直销渠道二部
		case 4:
			result = " orgId in (select id from com.hk.commons.entity.Organization where "
					+ "  code like '1-2-415-%' or code like  '1-2-428-%'"
					+ "or  code like '1-2-440-%' or code like  '1-2-442-%'"
					+ "or  code like '1-2-448-%' or code like  '1-2-414-%'"
					+ "or  code like '1-2-431-%' or code like  '1-2-436-%'))";
			break;
		// 居间渠道部
		case 5:
			result = " orgId in (select id from com.hk.commons.entity.Organization where "
					+ "  code like '1-2-423-%')";
			break;

		// 综合业务部
		case 6:
			result = " orgId in (select id from hcom.hk.commons.entity.Organization where "
					+ "  code like '1-2-434-%')";
			break;

		// 无主业务部
		case 7:
			result = " orgId is null and (recommendCode is null  or  recommendCode not in "
					+ "(select name from com.hk.commons.entity.sys.SysUser where orgId is not null))";
			break;
		default:
			break;
		}

		return result;
	}

	//create in 2016
	@Override
	public Integer getChannelById(Integer orgId) {
		Integer returnCode = 0;
		Organization organization = findById(orgId);
		if (organization != null
				&& StringHelper.isNotEmpty(organization.getCode())) {
			String orgCode = organization.getCode();
			
			//综合业务部
			if (orgCode.startsWith(ConstantUserChannel.CODE_ZONGHE)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_ZONGHE;
			//直销01
			} else if (orgCode.startsWith(ConstantUserChannel.CODE_ZHIXIAO_01)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_ZHIXIAO_01;
			//直销02
			} else if (checkZhiXiO02(orgCode)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_ZHIXIAO_02;
			//内渠01
			} else if (orgCode.startsWith(ConstantUserChannel.CODE_NEIQU_01)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_NEIQU_01;
			//内渠02
			} else if (orgCode.startsWith(ConstantUserChannel.CODE_NEIQU_02)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_NEIQU_02;
			//居间
			} else if (orgCode.startsWith(ConstantUserChannel.CODE_JUJIAN)) {
				returnCode = ConstantUserChannel.USER_CHANNEL_JUJIAN;
			} else {
				returnCode = ConstantUserChannel.USER_CHANNEL_WUZHU;
			}
		}
		return returnCode;
	}

	//create in 2016
	public Boolean checkZhiXiO02(String code){
		Boolean result = false;
		if(code.startsWith("1-2-415-")
				||code.startsWith("1-2-428-")
				||code.startsWith("1-2-440-")
				||code.startsWith("1-2-442-")
				||code.startsWith("1-2-448-")
				||code.startsWith("1-2-414-")
				||code.startsWith("1-2-431-")
				||code.startsWith("1-2-436-")
				){
			result = true; 
		}
		 
		return result;
	}

	//create in 2016
	private List<Organization>  getSubOrg(int id ){
		Organization org = findById(id);
		String orgCode = org.getCode();
		HqlFilter hqlFilter = new HqlFilter();
		hqlFilter.addSql(" where 1=1 and code like '" + orgCode + "%'");
		logger.info("hqlfilter = " + hqlFilter.getWhereAndOrderHql() );
		List<Organization>  subOrgList = findByFilter(hqlFilter);
		logger.info("subOrgList size = " + subOrgList.size());
		return subOrgList;
	}

	/**
	 * 获取部门的组织架构Code
	 */
	//create in 2016
	private String getDepCodeByDuties(Integer orgId){
		String depCode = "";


		if(orgId == 413){
			depCode = "1-2-3-";
		}else if(orgId == 177){
			depCode = "1-2-4-";
		}else if(orgId == 178){
			depCode = "1-2-5-";
		}else {
			Organization org = findById(orgId);
			depCode = org.getCode();
			depCode= depCode.replace(orgId.toString(), "");
		}
		logger.info("orgId ={}, depCode={}", orgId, depCode);
		return depCode;
	}




}
